package com.zz.yt.lib.bluetooth.delegate.printer;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.landicorp.android.eptapi.DeviceService;
import com.landicorp.android.eptapi.device.Printer;

import com.blankj.utilcode.util.ToastUtils;
import com.landicorp.android.eptapi.exception.ReloginException;
import com.landicorp.android.eptapi.exception.RequestException;
import com.landicorp.android.eptapi.exception.ServiceOccupiedException;
import com.landicorp.android.eptapi.exception.UnsupportMultiProcess;
import com.zz.yt.lib.bluetooth.R;
import com.zz.yt.lib.ui.CustomTitleBar;
import com.zz.yt.lib.ui.base.ui.LatteTitleDelegate;

/**
 * pda打印
 *
 * @author qf
 * @version 1.0
 **/
public class PrinterDelegate extends LatteTitleDelegate implements PrintLister {

    private AssistPrinterStep step;

    @NonNull
    public static PrinterDelegate create() {
        Bundle args = new Bundle();
        PrinterDelegate fragment = new PrinterDelegate();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void setCustomTitleBar(@NonNull CustomTitleBar titleBar) {
        titleBar.setText("pda打印");
    }

    @Override
    protected Object setLayout() {
        return R.layout.blu_delegate_added_print;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        super.onBindView(savedInstanceState, rootView);

        print();
    }


    /**
     * 开始打印
     */
    private void print() {

        PrinterContent printerContent = new PrinterContent();
        if (null == step) {
            step = new AssistPrinterStep(printerContent);
            step.setLister(this);
        }

        int ret = step.getPrinterStatus();
        if (ret != Printer.ERROR_NONE) {
            return;
        }
        step.init(getContext());
        step.addContent();
        step.startStepPrint();
    }

    @Override
    public void success() {
        ToastUtils.showShort("打印成功");
    }

    @Override
    public void filed() {
        ToastUtils.showShort("打印失败");
    }


    @Override
    public void onResume() {
        super.onResume();
        bindDeviceService();
    }

    @Override
    public void onPause() {
        super.onPause();
        unbindDeviceService();
    }

    public void bindDeviceService() {
        try {
            DeviceService.login(context);
        } catch (RequestException | ServiceOccupiedException | ReloginException | UnsupportMultiProcess e) {
            e.printStackTrace();
        }
    }


    public void unbindDeviceService() {
        DeviceService.logout();
    }
}
